package com.dsl.tms.service;

import com.dsl.tms.entity.redis.AdminRedis;
import com.dsl.tms.entity.response.ErrorLogger;
import com.dsl.tms.entity.response.IfSucessMap;
import com.dsl.tms.entity.response.ListMap;
import com.dsl.tms.entity.result.Result;
import com.dsl.tms.enums.AppResult;
import com.dsl.tms.repository.ErrorLoggerRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AppService {

    @Autowired
    private ErrorLoggerRepository errorLoggerDao;

    private static Logger LOGGER = LoggerFactory.getLogger(AppService.class);

    @Autowired
    private RedisTemplate redisTemplate;


    public IfSucessMap save_error_logger(com.dsl.tms.entity.request.ErrorLogger errorLogger, String token){
        IfSucessMap ifSucessMap = new IfSucessMap();
        Result result = new Result();
        com.dsl.tms.entity.db.ErrorLogger errorLoggerEntity = new com.dsl.tms.entity.db.ErrorLogger();
        errorLoggerEntity.setType(errorLogger.getType());
        errorLoggerEntity.setUrl(errorLogger.getUrl());
        errorLoggerEntity.setTime(errorLogger.getTime());
        errorLoggerEntity.setUserid(errorLogger.getUserId());
        errorLoggerEntity.setUsername(errorLogger.getUserName());
        errorLoggerEntity.setToken(errorLogger.getToken());
        try {
            errorLoggerDao.save(errorLoggerEntity);
        } catch (Exception e){
            e.printStackTrace();
            LOGGER.error(e.getMessage());
            result.setCode(AppResult.FAIL.getCode());
            result.setDescription(AppResult.FAIL.getDescription()+e.getMessage());
            ifSucessMap.setResult(result);
            return ifSucessMap;
        }

        result.setCode(AppResult.SECCESS.getCode());
        result.setDescription(AppResult.SECCESS.getDescription());
        ifSucessMap.setResult(result);
        return ifSucessMap;
    }

    public ListMap get_error_list(String token){
        ListMap listMap = new ListMap();
        AdminRedis adminRedis = (AdminRedis) redisTemplate.opsForValue().get(token);
        List<com.dsl.tms.entity.db.ErrorLogger> list = errorLoggerDao.findAllByUserid(adminRedis.getUserId());
        listMap.setList(list);
        Result result = new Result();
        result.setCode(AppResult.SECCESS.getCode());
        result.setDescription(AppResult.SECCESS.getDescription());
        listMap.setResult(result);
        return listMap;
    }
}
